<template>
  <el-cascader style="width: 400px;" v-model="regionIds" :props="list" :placeholder="placeholder" />
</template>
<script lang="ts" setup>
  import { AreaSubs,GetAreaDetails } from '@/api/area'
  import {ref , onMounted,watch} from 'vue'
  import type { CascaderProps } from 'element-plus'
  interface Props {
    modelValue:any,
    level:number
  }
  const props = withDefaults(defineProps<Props>(), {
        modelValue: '',
        text:'',
        level: 3
  })
  let text = ''
  const regionIds = ref<any>([])
  const placeholder = ref<string>('请选择地址')
  interface Emits { //定义事件
        (e: 'update:modelValue', value: any): void,
        (e: 'text', value: any): void,
        (e: 'cityid', value: any): void
        
  }
  const emit = defineEmits<Emits>()
  watch(()=>regionIds.value,() =>{
      emit('update:modelValue', regionIds.value[regionIds.value.length-1] )
      emit('text', text)
      emit('cityid', regionIds.value[1] )
  })
  watch(()=>props.modelValue,() =>{
    if(props.modelValue) {
      GetAreaDetails(props.modelValue).then((res:any) => {
          regionIds.value = res.data.fullIds
          placeholder.value = res.data.fullName
          text = res.data.fullName
        })
    }
    else {
      regionIds.value =[]
      placeholder.value =''
    }
     
  })

  onMounted(() => {
    
  })
 
 let id = 0
const list: CascaderProps = { //定义级联选择器的数据结构
  lazy: true,
  lazyLoad(node, resolve) {
    let parentId = 0
    if(node.value)
      parentId = Number(node.value)
    AreaSubs(parentId).then((res:any) =>{
          const nodes =  res.data.map((item:any) => ({
            value: item.id,
            label: item.name,
            leaf: (node.level >= props.level) || !item.hasChildren
        }))
        resolve(nodes)
    })
  },
}

</script>
